<?php
/**
 * Description of ConviteDAO
 *
 * @author Magno
 */
class ConviteDAO {

    private $conexao;
    private $statusDAO;
    private $clienteDAO;

    public function __construct() {
        $this->conexao = Conexao::getConexao();
        $this->statusDAO = new StatusDAO();
        $this->clienteDAO = new ClienteDAO();
    }

    public function salvar($convite) {

        try {

            if ($convite->getConviteID() != null && $convite->getConviteID() > 0) {

                $statment = $this->conexao->prepare("UPDATE convite SET
                        email = :email,
                        mensagem = :mensagem,
                        usuarioID = :usuarioID,
                        convidadoID = :convidadoID,
                        statusID = :statusID
                        WHERE conviteID = :conviteID");
            } else {

                $statment = $this->conexao->prepare("INSERT INTO convite(conviteID,email,mensagem,usuarioID,convidadoID,statusID)
                    VALUES (:conviteID,:email,:mensagem,:usuarioID,:convidadoID,:statusID);");
            }

            if ($statment->execute($convite->toBD())) {

                if ($convite->getConviteID() == null || $convite->getConviteID() <= 0)
                    $convite->setConviteID($this->conexao->lastInsertId());
                return $convite;
            }else {
                $erros = $statment->errorInfo();
                throw new Exception("Erro ConviteDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ConviteDAO:" . $err->getMessage());
        }
    }

    public function excluir($conviteID) {

        try {

            $statment = $this->conexao->prepare("DELETE FROM convite WHERE conviteID = :conviteID");
            $statment->bindParam(':conviteID', $conviteID);

            if (!$statment->execute()) {
                $erros = $statment->errorInfo();
                throw new Exception("Erro ConviteDAO: " . $erros[2]);
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ConviteDAO:" . $err->getMessage());
        }
    }

    public function listar($pagina = 0, $email = "", $usuarioID = -1, $statusID = -1, $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina);
            $where = $this->getWhere($email, $usuarioID, $statusID);
            $convites = array();
            $statment = $this->conexao->query("SELECT * FROM convite u $where $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $convite = new ConviteBean($row['conviteID'], $row['email'], $row['mensagem']);
                $convite->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $convite->setCliente ($this->clienteDAO->buscarPorID($row['usuarioID']));
                    if(isset ($row['convidadoID']) && $row['convidadoID'] > 0)
                        $convite->setConvidado($this->clienteDAO->buscarPorID($row['convidadoID']));
                }

                $convites[] =  $convite;
            }

            return $convites;
        } catch (PDOException $err) {
            throw new Exception("Erro ConviteDAO:" . $err->getMessage());
        }
    }

    public function listarPorOrdem($pagina = 0, $tamanho = 0, $ordem = "conviteID", $direcao = "ASC", $carregarDependencias = false) {
        try {

            $limite = Util::getPaginacao($pagina,$tamanho);
            $convites = array();
            $statment = $this->conexao->query("SELECT * FROM convite u ORDER BY u.$ordem $direcao $limite");

            foreach ($statment->fetchAll(PDO::FETCH_SERIALIZE) as $row){
                $convite = new ConviteBean($row['conviteID'], $row['email'], $row['mensagem']);
                $convite->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $convite->setCliente ($this->clienteDAO->buscarPorID($row['usuarioID']));
                    if(isset ($row['convidadoID']) && $row['convidadoID'] > 0)
                        $convite->setConvidado($this->clienteDAO->buscarPorID($row['convidadoID']));
                }

                $convites[] = $convite;
            }

            return $convites;
        } catch (PDOException $err) {
            throw new Exception("Erro ConviteDAO:" . $err->getMessage());
        }
    }

    public function buscarPorID($conviteID, $carregarDependencias = false) {
        try {

            $row = $this->conexao->query("SELECT * FROM convite WHERE conviteID = $conviteID ")->fetch(PDO::FETCH_SERIALIZE);

            if (isset ($row['conviteID']) && $row['conviteID'] > 0) {
                $convite = new ConviteBean($row['conviteID'], $row['email'], $row['mensagem']);
                $convite->setStatus($this->statusDAO->buscarPorID($row['statusID']));

                if($carregarDependencias){
                    $convite->setCliente ($this->clienteDAO->buscarPorID($row['usuarioID']));
                    if(isset ($row['convidadoID']) && $row['convidadoID'] > 0)
                        $convite->setConvidado($this->clienteDAO->buscarPorID($row['convidadoID']));
                }
                
                return $convite;
            } else {
                return null;
            }
        } catch (PDOException $err) {
            throw new Exception("Erro ConviteDAO:" . $err->getMessage());
        }
    }

    private function getWhere($email = "", $usuarioID = -1, $statusID = -1) {

        $where = " WHERE 1 = 1 ";

        if (isset($usuarioID) && $usuarioID > 0) {
            $where = $where . " AND u.usuario = $usuarioID ";
        }

        if (isset($email) && strlen($email) > 0) {
            $where = $where . " AND u.email like '%$email%' ";
        }

        if (isset($statusID) && $statusID > 0) {
            $where = $where . " AND u.statusID = $statusID ";
        }

        return $where;
    }

    public function total($email = "", $usuarioID = -1, $statusID = -1) {
        try {

            $where = $this->getWhere($email, $usuarioID, $statusID);
            $total = $this->conexao->query("SELECT COUNT(u.conviteID) total FROM convite u $where")->fetch(PDO::FETCH_COLUMN);
            return $total;
        } catch (PDOException $err) {
            throw new Exception("Erro ConviteDAO:" . $err->getMessage());
        }
    }

}
?>